<!--
 * @Description  :
 * @Autor        : guoxi
 * @Date         : 2022-06-29 14:08:57
 * @LastEditors  : Please set LastEditors
 * @LastEditTime : 2022-09-14 18:31:50
 * @FilePath     : \rpms\src\views\document\scientific\paper\index.vue
-->
<template>
  <div class="content">
    <el-card class="card-box">
      <div class="card-box--headerwrap">
        <el-page-header content="论文" @back="goback"></el-page-header>
        <div class="card-box--setbtn" v-if="isEdit">
          <el-button @click="goback">取消</el-button>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </div>
      </div>
    </el-card>
    <el-card class="card-box form-box">
      <el-form
        :disabled="!isEdit"
        :model="model.formData"
        ref="formRef"
        @submit.prevent
        :rules="model.formRules"
        label-width="160px"
      >
        <el-row>
          <el-col :xl="8" :lg="12">
            <el-form-item label="成果来源" prop="paperType">
              <el-select
                style="width: 100%"
                v-model="model.formData.paperType"
                clearable
                placeholder="请选择"
                value-key="id"
              >
                <el-option
                  v-for="(item, index) in model.paperTypes"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xl="8" :lg="12">
            <el-form-item label="论文名称" prop="paperName">
              <el-input v-model.trim="model.formData.paperName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="model.formData.paperType === '1'">
          <el-col :xl="8" :lg="12">
            <el-form-item label="所属项目" placeholder="请选择所属项目">
              <el-select
                style="width: 100%"
                v-model="model.formData.projectId"
                clearable
                placeholder="请选择"
                value-key="id"
                @change="handleSelected"
              >
                <el-option
                  v-for="item in projectList"
                  :key="item.id"
                  :label="item.projectName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xl="8" :lg="12">
            <el-form-item label="项目编号" prop="projectNum">
              <el-input
                disabled
                v-model.trim="model.formData.projectNum"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :xl="8" :lg="12">
            <el-form-item label="发表刊物" prop="publication">
              <el-input v-model.trim="model.formData.publication"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xl="8" :lg="12">
            <el-form-item label="刊物类型" prop="publicationType">
              <el-select
                style="width: 100%"
                v-model="model.formData.publicationType"
                clearable
                value-key="dicCode"
              >
                <el-option
                  v-for="item in model.publicationTypes"
                  :key="item.key"
                  :label="item.label"
                  :value="item.key"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :xl="8" :lg="12">
            <el-form-item label="期卷" prop="periodicals">
              <el-input v-model.trim="model.formData.periodicals"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xl="8" :lg="12">
            <el-form-item label="发表时间" prop="publishTime">
              <!-- <el-input v-model.trim="model.formData.publishTime"></el-input> -->
              <el-date-picker
                style="width: 100%"
                v-model="model.formData.publishTime"
                value-format="YYYY-MM-DD hh:mm:ss"
                type="date"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :xl="8" :lg="12">
            <el-form-item label="所属公司主体" prop="principalCompanyCode">
              <el-select
                v-model="model.formData.principalCompanyCode"
                clearable
                style="width: 100%"
                value-key="dicCode"
              >
                <el-option
                  id="default-option"
                  v-for="item in principalCompanyArr"
                  :key="item.dicCode"
                  :label="item.dicValue"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :xl="16" :lg="24">
            <el-form-item label="作者信息" prop="author">
              <SelectForTable
                @change="changeAuthor"
                ref="authorSelectTable"
                :value="model.formData.authorList"
                rankLable="作者排名"
              >
              </SelectForTable>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-row>
          <el-col>
            <el-form-item label="上传文档" prop="attachment">
              <el-upload
                name="uploadFile"
                multiple
                :accept="acceptTypes"
                :action="uploadComUrl"
                :headers="uploadHeaders"
                :on-success="handleSuccess"
                :on-remove="handleRemove"
                :on-error="handleError"
                :file-list="defaultFileList"
                :before-upload="beforeAvatarUpload"
                :on-preview="handlePreview"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    支持上传doc、docx、xls、xlsx、pdf、ppt、pptx、png、jpg、jpeg等格式文件,文件大小不得大于10M。
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row>
          <el-col>
            <el-form-item label="上传文档" prop="attachment">
              <ecm-upload
                :files="defaultFileList"
                :docid="model.docid"
                @setFile="handleSuccess"
              ></ecm-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <approval ref="approvalRef"></approval>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
// import { useRoute } from "vue-router";
import { addPaper, updatePaper, getPaperById } from "/@/api/document";
import { postProjectList } from "/@/api/project";
import EcmUpload from "/@/components/ecmUpload/index.vue";
import Approval from "../approval.vue";
import NotifMessage from "/@/utils/message/notification";
import SelectForTable from "/@/components/selectForTable/index.vue";
import { postDeptList } from "/@/api/dept";
import { postSysCompanyList } from "/@/api/organization";
import { useRoute, useRouter } from "vue-router";
import { postDictList } from "/@/api/common";
const approvalRef = ref<HTMLFormElement | null>(null) as any;
const router = useRouter();
const route = useRoute();
let model = reactive({
  docid: window["ecmDocType"].paper,
  mode: "Add",
  dialogFormVisible: false,
  data: [],
  loading: false,
  paperTypes: [
    { name: "项目", value: "1" },
    { name: "非项目", value: "2" }
  ],
  formData: {
    principalCompanyCode: null,
    projectNum: "",
    paperType: "",
    projectId: null,
    projectName:"",
    rdScientificId: null,
    paperName: "",
    publication: "",
    publicationType: "",
    periodicals: "",
    publishTime: "",
    author: null,
    authorDeptName: "",
    publishDept: "",
    authorRank: "",
    attachment: [],
    authorList: [],
    partakeUnit: [],
    publishDepts: null
  },
  publicationTypes: [
    { key: "SCI", label: "SCI" },
    { key: "EI", label: "EI" },
    { key: "中文核心期刊", label: "中文核心期刊" },
    { key: "中文核心期刊/SCI", label: "中文核心期刊/SCI" },
    { key: "中文核心期刊/EI", label: "中文核心期刊/EI" },
    { key: "其它", label: "其它" }
  ],
  authorRanks: [
    { key: "一", label: "一" },
    { key: "二", label: "二" },
    { key: "三", label: "三" },
    { key: "其它", label: "其它" }
  ],
  formRules: {
    paperType: [
      { required: true, message: "请选择成果来源", trigger: "change" }
    ],
    paperName: [
      { required: true, message: "请输入论文名称", trigger: "change" }
    ],
    publication: [
      { required: true, message: "请输入发表刊物", trigger: "change" }
    ],

    publicationType: [
      { required: true, message: "请选择发表刊物类型", trigger: "change" }
    ],

    periodicals: [{ required: true, message: "请输入期卷", trigger: "change" }],
    publishTime: [
      { required: true, message: "请选择发表时间", trigger: "change" }
    ],
    author: [{ required: true, message: "请选择作者", trigger: "change" }],
    principalCompanyCode: [
      { required: true, message: "请选择所属公司主体", trigger: "change" }
    ],
    attachment: [{ required: true, message: "请上传附件", trigger: "change" }]
    // authorDeptName: [
    //   { required: true, message: "请输入作者单位", trigger: "change" }
    // ],
    // authorRank: [
    //   { required: true, message: "请输入作者排名", trigger: "change" }
    // ]
  }
});

let authorSelectTable = ref(null);
const formRef = ref<HTMLFormElement | null>(null) as any;
// const deptTreePartakeRef = ref<HTMLElement | null>(null) as any;
let joinDeptList = ref([]);

let projectList = ref([]);
let defaultFileList = ref([]);
let principalCompanyArr = ref([]);

const initPrincipalCompanyList = async () => {
  try {
    const params = {
      dicType: "rd_principal_cmpy"
    };
    const { code, data } = await postDictList(params);
    if (code === 200) {
      principalCompanyArr.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};
const handleSelected = item => {
  const target = projectList.value.find(el => el.id === item);
  model.formData.projectNum = target.projectCode;
  model.formData.projectName = target.projectName;
};

// 获取项目信息
const getProjectList = async () => {
  try {
    const { code, data } = await postProjectList({ pageNum: 1, pageSize: 0 });
    if (code === 200) {
      projectList.value = data.list;
      model.formData.projectNum = data.list.find(
        el => el.id === model.formData.projectId
      )?.projectCode;
    }
  } catch (err) {
    console.log(err);
  }
};

const handleSuccess = res => {
  defaultFileList.value = res.file;
  model.formData.attachment = res.file;
  formRef.value.clearValidate();
};

const changeAuthor = arr => {
  model.formData.author = arr;
};

// const handleRemovePartake = event => {
//   model.formData.partakeUnit = model.formData.partakeUnit.filter(item => {
//     if (item.partakeUnitName !== event) {
//       return item;
//     }
//   });
//   deptTreePartakeRef.value.setCheckedKeys(
//     model.formData.partakeUnit.map(item => {
//       return item.partakeUnitCode;
//     })
//   );
// };

// const handleCheckChangePartake = () => {
//   const res = deptTreePartakeRef.value.getCheckedNodes();
//   const newData =
//     res.length &&
//     res.map(item => {
//       return {
//         partakeUnitCode: item.isEmp ? "-" : item.id,
//         partakeUnitName: item.deptDescShrt,
//         isEmp: item.isEmp
//       };
//     });
//   if (res.length) {
//     model.formData.partakeUnit = [newData[res.length - 1]];
//     model.formData.publishDepts = newData[res.length - 1].partakeUnitName;
//   } else {
//     model.formData.partakeUnit = [];
//     model.formData.publishDepts = [];
//   }
// };

const initDeptList = async () => {
  const { code, data } = await postDeptList({
    pageSize: 0
  });
  let deptList = [];
  if (code === 200) {
    deptList = data.map(item => {
      return {
        id: item.id,
        deptDescShrt: item.deptDescShrt,
        children: item.children
      };
    });
  }
  let companyList = [];
  const res = await postSysCompanyList({
    pageSize: 0
  });
  if (res.code === 200) {
    res.data.list.map(el => {
      companyList.push({
        id: el.id,
        deptDescShrt: el.companyName,
        isEmp: true
      });
    });
  }

  joinDeptList.value = [
    {
      deptDescShrt: "内部单位",
      disabled: true,
      children: deptList,
      id: "0-0"
    },
    {
      deptDescShrt: "外部单位",
      disabled: true,
      children: companyList,
      id: "0-1"
    }
  ];
};

const handleSubmit = async () => {
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  if (!isValid) return;
  // const paramsData
  const params = JSON.parse(JSON.stringify(model.formData));
  const participantList = authorSelectTable.value.participantList;
  params.authorList = participantList.map(el => {
    return {
      bizId: el.id,
      bizName: el.name,
      bizType: "1",
      bizRank: el.rank
    };
  });

  params.attachment = JSON.stringify(params.attachment);
  params.author = JSON.stringify(
    participantList.map(el => {
      let deptName =
        el.name.indexOf("-") !== -1
          ? ""
          : el.deptName
          ? "-" + el.deptName
          : "-无";
      return {
        id: el.id,
        userId: el.id,
        name: el.name + deptName,
        companyName: el.companyName || el.deptName,
        department: el.department || el.deptName,
        isEmp: el.isEmp,
        rank: el.rank
      };
    })
  );
  if (model.formData.paperType === "2") {
    params.projectId = null;
    params.projectNum = null;
  }
  if (+params.principalCompanyCode.dicCode > 2) {
    params["companyEntityCode"] = params.principalCompanyCode.dicCode;
    params["companyEntityName"] = params.principalCompanyCode.dicValue;
    params["companyEntityMaxCode"] = "3";
    params["companyEntityMaxName"] = "华润酒业";
  } else {
    params["companyEntityCode"] = params.principalCompanyCode.dicCode;
    params["companyEntityName"] = params.principalCompanyCode.dicValue;
    params["companyEntityMaxCode"] = params.principalCompanyCode.dicCode;
    params["companyEntityMaxName"] = params.principalCompanyCode.dicValue;
  }

  if (+params.principalCompanyCode.dicCode === 1) {
    params["companyEntityMaxName"] = "华润啤酒";
  }

  if (model.mode === "Add") {
    const { code, message,data } = await addPaper(params);
    if (code === 200) {
      const businessId = data;
      model.formData.name = model.formData.paperName;
      approvalRef.value.handleSubmit(businessId,model.formData,52);
    } else {
      NotifMessage.error(message);
    }
  } else {
    const { code, message } = await updatePaper(params);
    if (code === 200) {
      if(source && source === "back"){//驳回到第一步
        approvalRef.value.approvalSubmit(52);
      }
      else{//审批完之后，重新发起
        const businessId = route.query.rdScientificId;
        model.formData.name = model.formData.paperName;
        approvalRef.value.handleSubmit(businessId,model.formData,52);
      }
    } else {
      NotifMessage.error(message);
    }
  }
};

const goback = () => {
  router.push("/document/scientific?activeName=3");
};
const getData = async id => {
  defaultFileList.value = [];
  const { data } = await getPaperById(id);

  model.formData = data;
  model.formData.principalCompanyCode = {
    dicCode: data.companyEntityCode,
    dicValue: data.companyEntityName
  };
  model.formData.attachment = JSON.parse(model.formData.attachment as any);
  defaultFileList.value = model.formData.attachment;
  defaultFileList.value.map(el => {
    el["name"] = el.fileName;
  });
  model.formData.paperType = data.projectId ? "1" : "2";
  // model.formData.projectNum = route.query.projectNum as any;
  model.formData.authorList = JSON.parse(model.formData.author);
};
const id = route.query.id;
if (id) {
  model.mode = "Edit";
  getData(id);
}
const source = route.query.source;   //驳回到第一步，然后待办里面点击可以重新调到该页面，重新走流程审批
const isEdit = route.query.mode === "edit" ? true : false;
getProjectList();
initDeptList();
initPrincipalCompanyList();
</script>

<style lang="scss" scoped>
.content {
  .card-box--headerwrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .card-box--setbtn {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    width: 140px;
  }
}
</style>
